package com.yudean.esb.config;

import com.yudean.esb.cached.DataSourceScanner;
import com.yudean.esb.cached.ServicesCollection;
import com.yudean.esb.dao.esb.EsbServiceConfigDao;
import com.yudean.esb.dao.esb.EsbServiceMapperDao;
import com.yudean.esb.domain.esb.EsbServiceConfig;
import com.yudean.esb.domain.esb.EsbServiceMapper;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Component
@Order(value = 1)
public class DataLoader implements ApplicationRunner {

    @Resource
    private EsbServiceConfigDao esbServiceConfigDao;
    @Resource
    private EsbServiceMapperDao esbServiceMapperDao;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        //配置定时任务，防止数据库长时间没有访问导致报错
        Timer timer = new Timer();
        //延迟一毫秒执行第一次task,然后每隔一分钟执行一次task
        timer.schedule(new DataSourceScanner(), 1, 3600000);

        //加载数据库中的服务配置
        List<EsbServiceConfig> list = esbServiceConfigDao.getAll();
        for (EsbServiceConfig config : list) {
            String serviceID = config.getServiceID();
            //LOGGER.info("loadSerives():add Service ID ===>{}", serviceID);
            ServicesCollection.putService(serviceID, config);
        }

        Map<String, List<EsbServiceMapper>> mapList = esbServiceMapperDao.getServiceMapper();
        if (mapList != null) {
            Set<String> keyset = mapList.keySet();
            for (String key : keyset) {
                List<EsbServiceMapper> serviceMapperList = mapList.get(key);
                Map<String, String> map = new HashMap<>();
                for (EsbServiceMapper mapper : serviceMapperList) {
                    map.put(mapper.getTbColName(), mapper.getNodeName());
                }
                ServicesCollection.putMapper(key, map);
            }
        }

    }
}
